<template>
  <div class="box" ref="box" :style="{ width: contentWidth }">
    <span
      ref="content"
      class="content"
      @mouseenter="cursorEnter"
      @mouseleave="cursorLeave"
    >
      {{ data.text ? data.text : "通知内容" }}
    </span>
  </div>
</template>

<script>
export default {
  name: "NoticeBar",
  data() {
    return {
      data: this.options,
      box: "",
      content: "",
      //   定时器
      time: "",
      contentWidth: "",
    };
  },
  props: {
    options: {
      type: Object,
      default() {
        return {
          text: "滚动通知内111容",
        };
      },
    },
  },
  mounted() {
    this.textCarousel();
  },
  methods: {
    textCarousel() {
      this.box = this.$refs.box;
      this.content = this.$refs.content;
      let left = 0;
      let that = this;
      //   获取content的宽度
      this.contentWidth = this.content.offsetWidth;
      this.time = setInterval(() => {
        // 一次向左移动的距离
        left -= 5;
        // 当左移超过这个宽度时，重新设置left
        if (left <= -that.contentWidth) {
          left = 0;
        }
        that.content.style.left = left + "px";
      }, this.options.delay);
    },
    // 鼠标进入，停止定时器
    cursorEnter() {
      clearInterval(this.time);
    },
    // 鼠标离开，继续定时器
    cursorLeave() {
      this.textCarousel();
    },
  },
};
</script>
<style lang="scss" scoped>
.box {
  width: 160px;
  border: 1px solid black;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  .content {
    position: relative;
  }
}
</style>
